package com.lxmes.sales.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.lxmes.base.domain.JcIteminfo;
import com.lxmes.base.domain.NcSupplier;
import com.lxmes.base.mapper.JcIteminfoMapper;
import com.lxmes.base.mapper.NcSupplierMapper;
import com.lxmes.common.exception.ServiceException;
import com.lxmes.common.utils.DateUtils;
import com.lxmes.common.utils.NewNumber;
import com.lxmes.common.utils.SecurityUtils;
import com.lxmes.common.utils.StringUtils;
import com.lxmes.common.utils.bean.BeanUtils;
import com.lxmes.common.utils.bean.BeanValidators;
import com.lxmes.sales.domain.*;
import com.lxmes.sales.mapper.NcContractDetailMapper;
import com.lxmes.sales.mapper.NcQuotedPriceMapper;
import com.lxmes.sales.mapper.NcSalesOrderMapper;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lxmes.sales.mapper.NcContractMapper;
import com.lxmes.sales.service.INcContractService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;

/**
 * 合同管理表Service业务层处理
 *
 * @author ruoyi
 * @date 2022-11-29
 */
@Service
public class NcContractServiceImpl implements INcContractService
{
    @Autowired
    private NcContractMapper ncContractMapper;
    @Autowired
    private NcSalesOrderMapper salesOrderMapper;

    @Autowired
    private NcQuotedPriceMapper ncQuotedPriceMapper;

    @Autowired
    private NcContractDetailMapper ncContractDetailMapper;

    @Autowired
    private JcIteminfoMapper jcIteminfoMapper;

    @Autowired
    protected Validator validator;

    /**
     * 查询合同管理表
     *
     * @param uuid 合同管理表主键
     * @return 合同管理表
     */
    @Override
    public NcContract selectNcContractByUuid(String uuid)
    {
        NcContract ncContract = ncContractMapper.selectNcContractByUuid(uuid);
        NcContractDetail ncContractDetail = new NcContractDetail();
        ncContractDetail.setMainId(uuid);
        ncContract.setJcIteminfoList(ncContractDetailMapper.selectNcContractDetailList(ncContractDetail));
        return ncContract;
    }

    /**
     * 查询合同管理表列表
     *
     * @param ncContract 合同管理表
     * @return 合同管理表
     */
    @Override
    public List<NcContract> selectNcContractList(NcContract ncContract)
    {
        ncContract.setGcCode(SecurityUtils.getFactoryCode());
        List<NcContract> contractList = ncContractMapper.selectNcContractList(ncContract);
        List<NcContract> pushList = new LinkedList<>();
        for(NcContract ncContract1 : contractList){
            NcContractDetail ncContractDetail = new NcContractDetail();
            ncContractDetail.setMainId(ncContract1.getUuid());
            List<NcContractDetail> ncContractDetails = ncContractDetailMapper.selectNcContractDetailList(ncContractDetail);
            for(NcContractDetail ncContractDetail1 : ncContractDetails){
                NcContract ncContract2 = new NcContract();
                BeanUtils.copyProperties(ncContract1,ncContract2);
                BeanUtils.copyProperties(ncContractDetail1,ncContract2);
                pushList.add(ncContract2);

            }
        }
        return pushList;
    }

    @Override
    public List<NcContract> selectNcContractListContainItem(NcContract ncContract) {
        ncContract.setGcCode(SecurityUtils.getFactoryCode());
        List<NcContract> ncContracts = ncContractMapper.selectNcContractListContainItem(ncContract);
        return ncContracts;
    }

    /**
     * 新增合同管理表
     *
     * @param ncContract 合同管理表
     * @return 结果
     */
    @Override
    public int insertNcContract(NcContract ncContract)
    {
        String htNumber = "HT"+ NewNumber.createNewNumber(ncQuotedPriceMapper.getNewCode(DateUtils.getDate()));
        ncContract.setGcCode(SecurityUtils.getFactoryCode());
        ncContract.setGcName(SecurityUtils.getFactoryName());
        ncContract.setContractId(htNumber);
        ncContract.setUuid(UUID.randomUUID().toString());
        ncContract.setCreateTime(new Date());
        ncContract.setCreateBy(SecurityUtils.getUsername());
        ncContract.setDeptId(SecurityUtils.getDeptId());
        ncContractMapper.insertNcContract(ncContract);
        //添加主表
        List<NcContractDetail> jcIteminfoList = ncContract.getJcIteminfoList();
        if(jcIteminfoList!=null){
            for(NcContractDetail ncContractDetail : jcIteminfoList){
                ncContractDetail.setUuid(UUID.randomUUID().toString());
                ncContractDetail.setMainId(ncContract.getUuid());
                ncContractDetail.setItem(ncContractDetail.getItemCode());
                ncContractDetail.setContractUnitPrice(ncContractDetail.getUnitPrice());
                ncContractDetail.setContractNum(ncContractDetail.getYhNum());
                ncContractDetail.setCreateBy(SecurityUtils.getUsername());
                ncContractDetail.setCreateTime(new Date());
                ncContractDetailMapper.insertNcContractDetail(ncContractDetail);
            }
        }

        return 1;
    }

    /**
     * 修改合同管理表
     *
     * @param ncContract 合同管理表
     * @return 结果
     */
    @Override
    @Transactional
    public int updateNcContract(NcContract ncContract)
    {

        String uuid = ncContract.getUuid();
        ncContractDetailMapper.deleteNcContractDetailByMainId(uuid);
        List<NcContractDetail> jcIteminfoList = ncContract.getJcIteminfoList();
        for(NcContractDetail ncContractDetail : jcIteminfoList){
            ncContractDetail.setUuid(UUID.randomUUID().toString());
            ncContractDetail.setMainId(uuid);
            ncContractDetail.setItem(ncContractDetail.getItemId());
            ncContractDetail.setContractUnitPrice(ncContractDetail.getUnitPrice());
            ncContractDetail.setContractNum(ncContractDetail.getYhNum());
            ncContractDetailMapper.insertNcContractDetail(ncContractDetail);
        }
        return ncContractMapper.updateNcContract(ncContract);
    }

    /**
     * 批量删除合同管理表
     *
     * @param uuids 需要删除的合同管理表主键
     * @return 结果
     */
    @Override
    public int deleteNcContractByUuids(String[] uuids)
    {
        for(String uuid : uuids){
            NcContract ncContract = ncContractMapper.selectNcContractByUuid(uuid);
            if("0".equals(ncContract.getIsGenOrder())){
                ncContractMapper.deleteNcContractByUuid(uuid);
                ncQuotedPriceMapper.updatePrice("0",ncContract.getBjdH());
            }else{
                throw new RuntimeException("该合同已经生成订单不能删除！");
            }
        }
        return 1;
    }

    /**
     * 删除合同管理表信息
     *
     * @param uuid 合同管理表主键
     * @return 结果
     */
    @Override
    public int deleteNcContractByUuid(String uuid)
    {
        return ncContractMapper.deleteNcContractByUuid(uuid);
    }

    @Override
    @Transactional
    public int scOrder(NcContract ncContract) {
        String xsdd = "XSDD"+ NewNumber.createNewNumber(ncContractMapper.getNewCode(DateUtils.getDate()));
        List<NcContractDetail> ncContractDetails =ncContract.getJcIteminfoList();
        for(NcContractDetail detail : ncContractDetails){
            NcSalesOrder ncSalesOrder = new NcSalesOrder();
            ncSalesOrder.setOrderNumber(xsdd);
            ncSalesOrder.setFactoryName(ncContract.getGcName());
            ncSalesOrder.setFactoryCode(ncContract.getGcCode());
            ncSalesOrder.setOrderType("1");
            ncSalesOrder.setContractNo(ncContract.getContractId());
            ncSalesOrder.setNumber(detail.getContractNum().longValue());
            ncSalesOrder.setDeliveryDate(ncContract.getContractJhDate());
//            ncSalesOrder.setODeliveryDate(ncContract.getContractJhDate()+"");
            ncSalesOrder.setClientNo(ncContract.getHbCode());
            ncSalesOrder.setClientName(ncContract.getHbName());
            ncSalesOrder.setCreateTime(new Date());
            ncSalesOrder.setCreateBy(SecurityUtils.getUsername());
            ncSalesOrder.setProductModel(detail.getSpec());
            ncSalesOrder.setItemCode(detail.getItem());
            ncSalesOrder.setItemSubCode(detail.getItem());
            ncSalesOrder.setItemName(detail.getItemName());
            ncSalesOrder.setUnit(detail.getUnit());
            ncSalesOrder.setContractUnitPrice(detail.getContractUnitPrice());
            ncSalesOrder.setJhUnitPrice(detail.getJhUnitPrice());
            ncSalesOrder.setDeptId(SecurityUtils.getDeptId());
            salesOrderMapper.insertNcSalesOrder(ncSalesOrder);
        }
        ncContract.setIsGenOrder("1");
        ncContractMapper.updateNcContract(ncContract);
        return 1;
    }

    @Override
    public String imporIteminfo(List<JcIteminfo> infoList, boolean updateSupport, String operName,NcContract ncContract) {
        //导入物料信息表 无则插入有责不动
        if (StringUtils.isNull(infoList) || infoList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (JcIteminfo jcIteminfo : infoList)
        {
            try
            {
                BeanValidators.validateWithException(validator, jcIteminfo);
                jcIteminfo.setCreateBy(operName);
                jcIteminfo.setUpdateBy(operName);
                JcIteminfo jcIteminfo1 = jcIteminfoMapper.selectJcIteminfoByItemCode(jcIteminfo.getItemCode());
                if(StringUtils.isNull(jcIteminfo1)){
                    jcIteminfoMapper.insertJcIteminfo(jcIteminfo);
                }
                successNum++;
                successMsg.append("<br/>" + successNum + "数据导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/> 数据导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        ArrayList<NcContractDetail> detailList = new ArrayList();
        for(JcIteminfo jcIteminfo : infoList){
            NcContractDetail ncContractDetail = new NcContractDetail();
            BeanUtils.copyProperties(jcIteminfo,ncContractDetail);
            ncContractDetail.setUnitPrice(jcIteminfo.getPrice());
            ncContractDetail.setJhUnitPrice(jcIteminfo.getPrice());
            detailList.add(ncContractDetail);
        }
        ncContract.setJcIteminfoList(detailList);
        this.insertNcContract(ncContract);

        return successMsg.toString();
    }

    @Override
    public List<NcContractDetail> selecgetContractDetailByUuid(String uuid) {
        NcContractDetail ncContractDetail = new NcContractDetail();
        ncContractDetail.setMainId(uuid);
        return ncContractDetailMapper.selectNcContractDetailList(ncContractDetail);
    }
}
